package de.mmis.core.base.abstracttree.serializer.internal;

import java.util.Map;

import de.mmis.core.base.DeserializableAnnotations.DeserializationMethod;
import de.mmis.core.base.Position;
import de.mmis.core.base.abstracttree.InnerNode;
import de.mmis.core.base.abstracttree.LeafNode;
import de.mmis.core.base.abstracttree.LeafNode.Encoding;
import de.mmis.core.base.abstracttree.Tree;
import de.mmis.core.base.abstracttree.Tree.Type;
import de.mmis.core.base.abstracttree.serializer.AbstractSerializer;
import de.mmis.core.base.abstracttree.serializer.DeserializableException;
import de.mmis.core.base.gclass.GClass;

/**
 * Serializer class for (de)serializing {@link Position}s from/to Trees
 * 
 * @author Christian Koch
 */
public class GClassSerializer extends AbstractSerializer<GClass> {

	@DeserializationMethod
	public static GClass deserialize(Tree[] exp, ClassLoader classLoader,
			String id, Map<String, Object> idmap)
			throws DeserializableException {

		if (exp.length != 1)
			throw new DeserializableException(new InnerNode(exp),
					"GClass Tree needs 1 parameter");

		if (exp[0].getType() != Type.LEAF
				|| ((LeafNode) exp[0]).getEncoding() != Encoding.Quoted)
			throw new DeserializableException(new InnerNode(exp),
					"GClass Tree is no quoted atom");

		return getAtomClass((LeafNode) exp[0], classLoader);
	}

	public static GClass getAtomClass(LeafNode exp, ClassLoader classLoader)
			throws DeserializableException {
		String gclassString = exp.getUTF8Data();
		try {
			return GClass.fromString(gclassString, classLoader);
		} catch (ClassNotFoundException e) {
			throw new DeserializableException(exp, e, "gclass " + gclassString
					+ " cannot be loaded");
		}
	}

	@Override
	public Tree serializeInternal(GClass gclass, boolean explicit,
			Map<Object, String> refmap, ClassLoader classLoader) {
		return new LeafNode(gclass.toString(), Encoding.Quoted);
	}

	@Override
	public String getTypeIdentifier() {
		return "java-gclass";
	}
}
